package com.bjfu.demo.metric;


import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.StopWatch;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.context.annotation.Configuration;

@Slf4j
@Aspect
@Configuration
public class TimeTrackAspectConfig {

    @Around(value = "@annotation(com.bjfu.demo.metric.TrackTime)")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        StopWatch clock = new StopWatch();
        clock.start();
        try {
            return joinPoint.proceed();
        } finally {
            clock.stop();
            log.info("method:{} -> time:{}ms.",
                     joinPoint.getSignature().toShortString(), clock.getTime());
        }
    }

    @Around(value = "@annotation(com.bjfu.demo.metric.TrackTimeAttachedParameter)")
    public Object around2(ProceedingJoinPoint joinPoint) throws Throwable {
        StopWatch clock = new StopWatch();
        clock.start();
        try {
            return joinPoint.proceed();
        } finally {
            clock.stop();
            log.info("method:{} -> time:{}ms. params:{}.",
                    joinPoint.getSignature().toShortString(), clock.getTime(),
                    JSONObject.toJSONString(joinPoint.getArgs()));
        }
    }
}
